﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Evan
{
    /// <summary>
    /// 处理数据类型转换、数制转换、编码转换相关的类  
    /// </summary>
    public class ConvertHelper
    {
        #region 通用类型转换 ChangeType

        public static object ChangeType(object obj, Type conversionType)
        {
            return ChangeType(obj, conversionType, Thread.CurrentThread.CurrentCulture);
        }
        public static object ChangeType(object obj, Type conversionType, IFormatProvider provider)
        {
            Type nullableType = Nullable.GetUnderlyingType(conversionType);
            if (nullableType != null)
            {
                if (obj == null)
                {
                    return null;
                }
                return Convert.ChangeType(obj, nullableType, provider);
            }
            if (typeof(System.Enum).IsAssignableFrom(conversionType))
            {
                return Enum.Parse(conversionType, obj.ToString());
            }
            if (typeof(System.Guid).IsAssignableFrom(conversionType))
            {
                return Guid.Parse(obj.ToString());
            }
            return Convert.ChangeType(obj, conversionType, provider);
        }
        #endregion

        #region string和byte[] 转换
        /// <summary>  
        /// 使用指定字符集将string转换成byte[]  
        /// </summary>  
        /// <param name="text">要转换的字符串</param>  
        /// <param name="encoding">字符编码</param>  
        public static byte[] StringToBytes(string text, Encoding encoding)
        {
            return encoding.GetBytes(text);
        }
        /// <summary>  
        /// 使用指定字符集将byte[]转换成string  
        /// </summary>  
        /// <param name="bytes">要转换的字节数组</param>  
        /// <param name="encoding">字符编码</param>  
        public static string BytesToString(byte[] bytes, Encoding encoding)
        {
            return encoding.GetString(bytes);
        }
        #endregion

        #region 将byte[]转换成int  
        /// <summary>  
        /// 将byte[]转换成int  
        /// </summary>  
        /// <param name="data">需要转换成整数的byte数组</param>  
        public static int BytesToInt32(byte[] data)
        {
            //如果传入的字节数组长度小于4,则返回0  
            if (data.Length < 4)
            {
                return 0;
            }

            //定义要返回的整数  
            int num = 0;

            //如果传入的字节数组长度大于4,需要进行处理  
            if (data.Length >= 4)
            {
                //创建一个临时缓冲区  
                byte[] tempBuffer = new byte[4];

                //将传入的字节数组的前4个字节复制到临时缓冲区  
                Buffer.BlockCopy(data, 0, tempBuffer, 0, 4);

                //将临时缓冲区的值转换成整数，并赋给num  
                num = BitConverter.ToInt32(tempBuffer, 0);
            }

            //返回整数  
            return num;
        }
        #endregion
    }
}
